package com.ruisi.thumbnail;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;

/**
 * 下载的Runnable
 * @author spring ming
 *
 */
public class DownloadRunnable implements Runnable {
	
	public static final int DOWNLOAD_SUCCESS = 0;
	public static final int DOWNLOAD_FAIL    = 1;
	
	private DownloadTask mTask;
	private Handler mCallbackHandler;
	/**
	 * 构造函数
	 * @param downloadUrl        需要下载的url
	 * @param localPath          本地路径
	 * @param listener           启动下载的监听者
	 * @param callbackHandlers   回调用的handler
	 */
	DownloadRunnable(DownloadTask task, 
					 Handler callbackHandler){
		super();
		
		mTask            = task;
		mCallbackHandler = callbackHandler;
	}
	
	@Override
	public void run() {
		URL url = null;
		try {
			url = new URL(mTask.mDownloadUrl);
		} catch (MalformedURLException e) {
			mCallbackHandler.obtainMessage(DOWNLOAD_FAIL, ThumbnailManager.ERR_URL_ILIGEAL, 0, mTask).sendToTarget();
			return;
		}
		
		// 创建输出流
		File file = new File(mTask.mLocalPath + ".tmp");
		try {
			file.createNewFile();
		} catch (IOException e2) {
			e2.printStackTrace();
			mCallbackHandler.obtainMessage(DOWNLOAD_FAIL, -1, 0, mTask).sendToTarget();
			return;
		}
		
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file);
		} catch (FileNotFoundException e1) {
			mCallbackHandler.obtainMessage(DOWNLOAD_FAIL, -1, 0, mTask).sendToTarget();
			return;
		}
		
		// 下载文件
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			
			int len = 0;
			byte[] buffer = new byte[1024];
			while((len = is.read(buffer)) > 0){
				os.write(buffer, 0, len);
			}
			
		} catch (IOException e) {
			mCallbackHandler.obtainMessage(DOWNLOAD_FAIL, -1, 0, mTask).sendToTarget();
			return;
		} finally{
			if(null != conn){
				conn.disconnect();
			}
		}
		
		// 关闭输出流
		try {
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		File newFile = new File(mTask.mLocalPath);
		file.renameTo(newFile);
		Bitmap bmp = BitmapFactory.decodeFile(mTask.mLocalPath);
		if(null == bmp){
			mCallbackHandler.obtainMessage(DOWNLOAD_FAIL, -1, 0, mTask).sendToTarget();
		}else{
			mTask.mBitmap = bmp;
			mCallbackHandler.obtainMessage(DOWNLOAD_SUCCESS, 0, 0, mTask).sendToTarget();
		}
		
	}
	

}
